// 私有变量
const addBtn = document.querySelector('#add-btn');
const modal = document.querySelector('.modal');
const closeModalBtn = document.querySelector('#close-form-btn');
const tbody = document.querySelector('tbody');
const form = document.querySelector('#item-form');
const searchBox = document.querySelector("#search-box");
const formTitle = document.querySelector("#form-title");

// 表单选项
//#######################改改改################################
let flowerId = document.querySelector("#flowerID");
let flowerName = document.querySelector("#flowerName");
let category = document.querySelector("#category");
let price = document.querySelector("#price");
//#############################################################


let data = [];

const API_BASE_URL = "http://localhost/flowers";  // #### 改改改 ####

// 搜索功能
function search(name) {
    axios.get(API_BASE_URL + `?name=${name}`).then(res => {
        data = res.data;
        renderTable(data);
    });
}

// 渲染表格数据 # 修改item.后面的属性名称
function renderTable(data) {
    if (data.length === 0) return alert("无内容");
    tbody.innerHTML = data.map(item => {
        return `<tr data-id="${item.flowerId}">
                <td>${item.flowerId}</td>
                <td>${item.flowerName}</td>
                <td>${item.category}</td>
                <td>${item.price}</td>
                <td>
                    <button class="update-btn">修改</button>
                    <button class="delete-btn">删除</button>
                </td>
            </tr>`;
    }).join('');

    // 添加事件监听器（事件委托）
    tbody.addEventListener('click', handleTableClick);
}

// 更新，先回显要被修改的旧数据
function update(id) {
    axios.get(API_BASE_URL + `/${id}`).then(res => {
        const data = res.data;
        showOrCloseModal();
        form.reset();

        // ########以下内容要修改##########

        // formTitle.innerText = '更新图书';
        formTitle.innerText = '更新鲜花';
        flowerId.value = data.flowerId;
        flowerName.value = data.flowerName;
        category.value = data.category;
        price.value = data.price;

        //  ######以上内容要修改#####
    });
}


// 处理表格点击事件
function handleTableClick(e) {
    if (e.target.classList.contains('delete-btn')) {
        deleteItem(e.target.closest('tr').dataset.id);
    } else if (e.target.classList.contains('update-btn')) {
        update(e.target.closest('tr').dataset.id);
    }
}

// 开关浮层
function showOrCloseModal(show = true) {
    if (show) {
        modal.style.display = 'block';
    } else {
        modal.style.display = 'none';
    }

    flowerId.value = null; // 重置当前编辑的图书ID

}

// 获取列表
function fetch() {
    axios.get(API_BASE_URL).then(res => {
        console.log(res)
        data = res.data;
        renderTable(data);
    });

}

// 根据id删除
function deleteItem(id) {
    if (!confirm("真的要删除吗?")) return;
    axios.delete(API_BASE_URL + `/${id}`).then(res => {
        alert("删除成功！")
        fetch();
    });
}


// 点击保存按钮：添加或更新图书
function save() {

    // 获取表单项的值######改改#####
    console.log(flowerID);
    // 非空判断
    if (!flowerName.value || !category.value || !price.value) {
        alert("所有字段都必须填写！");
        return;
    }
    // 表单项的值，封装成一个对象
    const item = {
        flowerId: flowerId.value || null, // 如果为空，则视为添加新图书
        flowerName: flowerName.value,
        category: category.value,
        price: price.value
    };

    // 根据编号判断是添加还是更新
    if (flowerId.value!='') {
        console.log(item,6666);
        axios.put(API_BASE_URL, item).then(res => {
            alert("修改成功")
            fetch();
            showOrCloseModal(false);
        })
    } else {
        axios.post(API_BASE_URL, item).then(res => {
            alert("添加成功")
            fetch();
            showOrCloseModal(false);
        })
    }

}


// 初始化事件监听器
function init() {
    addBtn.addEventListener('click', () => {
        form.reset();
        // formTitle.innerText = '添加图书';
        formTitle.innerText = '添加鲜花';
        showOrCloseModal();
    });

    closeModalBtn.addEventListener('click', () => {
        flowerId.value = null;  //### 初始化id
        showOrCloseModal(false);
    });

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        save();
    });

    searchBox.addEventListener('keyup', (e) => {
        if (e.key === "Enter") {
            search(searchBox.value);
            searchBox.value = '';
        }
    });

    // 初始加载列表
    fetch();
}

// 执行初始化函数
init();
